package com.cheng.example.geektime.designpatterns.j57;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



public class UserController {

    private UserService userService = new UserService();

    //第二种方式，使用线程池
    private Executor executor;

    private List<RegObserver> regObservers = new ArrayList<>();

    public UserController(Executor executor) {
        this.executor = executor;
    }

    //一次性设置好，之后也不可能动态的修改
    public void setRegObservers(List<RegObserver> observers) {
        regObservers.addAll(observers);
    }

    public Long register(String telephone, String password) {
        long userId = userService.register(telephone, password);
        for (RegObserver observer : regObservers) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    observer.handleRegSuccess(userId);
                }
            });
        }

        return userId;
    }


    public static void main(String[] args) {

        //创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        UserController userController = new UserController(executorService);

        List<RegObserver> regObservers = new ArrayList<>();
        regObservers.add(new RegNotificationObserver());
        regObservers.add(new RegPromotionObserver());

        userController.setRegObservers(regObservers);
        userController.register("17513137853", "123456");

        executorService.shutdown();
    }

}
